package org.ben.waitnotify;

import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class WaitTest {
    @Test
    public void testA() {
        B b = new B();
        A a = new A("readerthread1", b);
        A a1 = new A("readerthread2", b);
        C c = new C(b);
        a.start();
        a1.start();
        c.start();
        try {
            a.join();
            a1.join();
            c.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class A extends Thread {
    private B b;
    private String name;

    A(String name, B b) {
        this.name = name;
        this.b = b;
    }

    @Override
    public void run() {
        synchronized(b) {
            System.out.println(name + " started...");
            if(null == b.getName()) {
                System.out.println(name + " is waiting...");
                try {
                    b.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(name + " starts reading " + b.getName());
        }
    }
}

class C extends Thread {
    private B b;
    C(B b) {
        this.b = b;
    }

    @Override
    public void run() {
        System.out.println("writter started...");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized(b) {
            if(null == b.getName()) {
                b.setName("setted the name...");
            }
            b.notify();
//            b.notifyAll();
        }
    }
}

class B {
    private String name;
    private int age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}